// gamecore.cpp
#include "gamecore.h"
#include <algorithm>
#include <QDebug>

GameCore::GameCore(QObject *parent) : QObject(parent) {}

void GameCore::initialize(const MapData &mapData) {
    m_originalMap = mapData;
    resetLevel();  // 复用重置逻辑
}

void GameCore::resetLevel() {
    // 强制从原始地图重新加载，彻底清除冗余数据
    m_currentMap = m_originalMap;
    m_playerPos = m_originalMap.playerStartPos;
    m_moveCount = 0;
    m_state = GameState::Running;

    // 额外检查：确保当前地图中箱子数量与目标点一致（清除冗余）
    int boxCount = 0;
    for (int i = 0; i < m_currentMap.rows; ++i) {
        for (int j = 0; j < m_currentMap.cols; ++j) {
            if (m_currentMap.grid[i][j] == MapElement::Box ||
                m_currentMap.grid[i][j] == MapElement::BoxOnTarget) {
                boxCount++;
            }
        }
    }
    // 如果箱子数超过目标点，强制清除多余的箱子（重置为空地）
    if (boxCount > m_currentMap.targetPositions.size()) {
        int excess = boxCount - m_currentMap.targetPositions.size();
        for (int i = 0; i < m_currentMap.rows && excess > 0; ++i) {
            for (int j = 0; j < m_currentMap.cols && excess > 0; ++j) {
                if (m_currentMap.grid[i][j] == MapElement::Box) {
                    m_currentMap.grid[i][j] = MapElement::Floor;
                    excess--;
                }
            }
        }
    }

    emit gameStateChanged(m_state);
    emit mapUpdated();
    emit moveCountChanged(m_moveCount);
}

bool GameCore::isValidPosition(int x, int y) const {
    return x >= 0 && x < m_currentMap.rows && y >= 0 && y < m_currentMap.cols;
}

bool GameCore::movePlayer(Direction direction) {
    if (m_state != GameState::Running) return false;

    int dx = 0, dy = 0;
    switch (direction) {
        case Direction::Up: dx = -1; break;
        case Direction::Down: dx = 1; break;
        case Direction::Left: dy = -1; break;
        case Direction::Right: dy = 1; break;
    }

    int newX = m_playerPos.x() + dx;
    int newY = m_playerPos.y() + dy;

    if (!isValidPosition(newX, newY)) return false;

    auto &cell = m_currentMap.grid[newX][newY];
    bool moved = false;

    // 处理箱子推动（核心修复：原位置必须清空）
    if (cell == MapElement::Box || cell == MapElement::BoxOnTarget) {
        int boxNewX = newX + dx;
        int boxNewY = newY + dy;

        if (isValidPosition(boxNewX, boxNewY)) {
            auto &boxCell = m_currentMap.grid[boxNewX][boxNewY];
            if (boxCell == MapElement::Floor || boxCell == MapElement::Target) {
                // 1. 清除箱子原位置的标记（关键！）
                m_currentMap.grid[newX][newY] = (cell == MapElement::BoxOnTarget)
                    ? MapElement::Target  // 原位置是目标点，重置为目标点
                    : MapElement::Floor;   // 原位置是空地，重置为空

                // 2. 设置箱子新位置的标记
                boxCell = (boxCell == MapElement::Target)
                    ? MapElement::BoxOnTarget
                    : MapElement::Box;

                // 3. 移动玩家
                updatePlayerPosition(m_playerPos.x(), m_playerPos.y(), newX, newY);
                moved = true;
            }
        }
    }
    // 处理普通移动（无箱子）
    else if (cell == MapElement::Floor || cell == MapElement::Target) {
        updatePlayerPosition(m_playerPos.x(), m_playerPos.y(), newX, newY);
        moved = true;
    }

    if (moved) {
        m_moveCount++;
        emit moveCountChanged(m_moveCount);
        updateGameState();
        emit mapUpdated();

        qDebug() << "GameCore: 玩家移动到" << m_playerPos.x() << "," << m_playerPos.y();

    }

    return moved;
}

// 在 GameCore::updatePlayerPosition 中（已实现但需确认）
void GameCore::updatePlayerPosition(int oldX, int oldY, int newX, int newY) {
    // 原位置：清除玩家标记
    auto &oldCell = m_currentMap.grid[oldX][oldY];
    if (oldCell == MapElement::Player) {
        oldCell = MapElement::Floor;  // 原位置是空地 → 重置为空
    } else if (oldCell == MapElement::PlayerOnTarget) {
        oldCell = MapElement::Target;  // 原位置是目标点 → 重置为目标点
    }

    // 新位置：设置玩家标记
    auto &newCell = m_currentMap.grid[newX][newY];
    if (newCell == MapElement::Floor) {
        newCell = MapElement::Player;  // 新位置是空地 → 设为玩家
    } else if (newCell == MapElement::Target) {
        newCell = MapElement::PlayerOnTarget;  // 新位置是目标点 → 设为目标点上的玩家
    }
    // 打印旧位置和新位置的网格元素
    qDebug() << "GameCore: 旧位置 (" << oldX << "," << oldY << ") 元素："
             << static_cast<int>(m_currentMap.grid[oldX][oldY]);
    qDebug() << "GameCore: 新位置 (" << newX << "," << newY << ") 元素："
             << static_cast<int>(m_currentMap.grid[newX][newY]);
    m_playerPos = QPoint(newX, newY);  // 更新 GameCore 中的当前位置
}

bool GameCore::checkLevelCompleted() const {
    // 检查所有目标点上是否都有箱子
    for (const auto &pos : m_currentMap.targetPositions) {
        auto cell = m_currentMap.grid[pos.x()][pos.y()];
        if (cell != MapElement::BoxOnTarget) return false;
    }
    return true;
}

void GameCore::updateGameState() {
    if (checkLevelCompleted()) {
        m_state = GameState::Completed;
        emit gameStateChanged(m_state);
    }
}
